<!-- 
    列表组件封装
    2022-8-15 by meikun
    1、基础功能：行、列、点击选中事件、行操作
    2、表头配置、支持表头点击排序、列表宽度配置、宽度填充
    3、列多选
    4、列宽移动
-->

<script setup lang="ts">
import {defineProps,defineEmits,defineExpose,ref} from 'vue'
import utils from '../utils/utils'

const tableData = defineProps({
    columns:{
        type: [Array],
        default: [{label:'测试1',field:'name',textAlign:'center',width:'100px'},{label:'测试2',field:'num',textAlign:'center'}],
        require: true
    },
    data:{
        type: [Array],
        default:[{name:'测试1',num:100},{name:'测试',num:100},{name:'测试',num:100},{name:'测试1',num:100},{name:'测试',num:100},{name:'测试',num:100}],
        require:true
    },
    oddEven:{
        type: [Boolean],
        default: false
    }
})

const data = ref(tableData.data)

//点击获取行、单元格数据
const chooseHandle = function(row,col){
    debugger
}

//根据列头排序
const sortByField = function(field){
    utils.sortByKey(data.value,field)
}

</script>

<template>
    <main>
        <table class="m-table">
            <tr class="head-tr">
                <th v-for="(item,i) in tableData.columns" :key="i"
                    :style="'width:' + item.width"
                    @click="sortByField(item)"
                >
                    {{item.label}}
                </th>
            </tr>
            
            <tr class="row-tr" v-for="(item,i) in data" :key="i"
                :class="i%2==0?'odd':'even'"
            >
                <td v-for="(column,k) in tableData.columns" :key="k" 
                    :style="'text-align:' + column.textAlign"
                    @click="chooseHandle(item,item[column.field])"
                >
                    {{item[column.field]}}
                </td>
            </tr>
            
        </table>
    </main>
</template>

<style lang="less" scoped>
.m-table{
    border-spacing: 0px;
    border-collapse: collapse;
    td{
        border: 1px solid darkgray;
    }
    .head-tr{
        height: 2.5rem;
        background-color: aliceblue;
        th{
            width: 5rem;
            border: 1px solid darkgray;
        }
    }
    .row-tr{
        border: 1px solid darkgray;
        .choosen{
            background-color: antiquewhite;
        }
    }
        .even{
            background-color:cornsilk;
        }
    
}
</style>